package demo_0416.hwzx;

import demo_0416.hw.Account;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class BankAccounts {
    private Map<Integer, Account> accounts;
    private static final String DATA_FILE = "resource/accounts.txt";
    private static final String PRINT_FILE = "resource/print.txt";
    public BankAccounts() {
        accounts = new HashMap<>();
        loadAccounts();
    }

    private void loadAccounts() {
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(DATA_FILE))) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                String[] strings = line.split(" ");
                int id = Integer.parseInt(strings[0]);
                String firstname = strings[1];
                String lastname = strings[2];
                double balance = Double.parseDouble(strings[3]);
                accounts.put(id,new Account(id, firstname, lastname, balance));
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void saveAccounts() {
        try {
            PrintWriter printWriter = new PrintWriter(new FileWriter(DATA_FILE));
            for (Account account : accounts.values()) {
                printWriter.println(account.getId() + " " + account.getFirstName() + " " + account.getLastName() + " " + account.getBalance());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void displayAccounts() {
        if (accounts.isEmpty()) {
            System.out.println("没有账户");
            return;
        }
        for (Account account : accounts.values()) {
            System.out.println(account.getId() + " " + account.getFirstName() + " " + account.getLastName() + " " + account.getBalance());
        }
    }

    public void updateAccount(int id, String firstname, String lastname, double balance) {
        if (accounts.containsKey(id)) {
            accounts.put(id,new Account(id,firstname,lastname,balance));
        }
        saveAccounts();
    }

    public void addAccount(Account account) {
        accounts.put(account.getId(),account);
        saveAccounts();
    }

    public void deleteAccount(int id) {
        accounts.remove(id);
        saveAccounts();
    }

    public void generateReport() {
        try (PrintWriter pw = new PrintWriter(new FileWriter(PRINT_FILE))) {
            pw.println("ID\tFirst Name\tLast Name\tbalance");
            for (Account account : accounts.values()) {
                pw.println(account.getId() + "\t" + account.getFirstName() + "\t" + account.getLastName() + "\t" + account.getBalance());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
